import Common from '../../common/common.js';
let common = new Common;
const app = getApp();

Page({
  data: {
    liveActivityInfo: 0, //直播活动详情
    isSpecial: 0, //特殊名片
    deliverNum: 0, //红点
    yuanNum: 0, //元春活动红点
    imgUrl: common.imgUrl,
    orgSeq: '',
    userId: '',
    stroeInfo: {},
    userInfo: {},
    user: '',
    // canvas 定义
    width: 355,
    height: 208,
    shopCard: '', //店铺名片
    imgUrl: common.imgUrl,
    isDisable: false, //防止多次点击
    background: '',
    ecode: "",
    doorwayPic: '',
    storeDesc: '',
    cardName: '',
    tagsNum: '', //判断品鉴酒兑换管理数量
    total: '', //常见问题数量
    wxUsername: '', //主播微信号
    showApproveModel: false, //认证弹窗
    creatModelShow: false, //创建直播显示弹窗
    approveImage: ''
  },
  // 绘制商品名片
  canvasKapian() {
    wx.getSetting({
      success: res => {
        console.log(res);
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success: res => {
              this.canvasClick();
            },
            fail: err => {
              wx.showModal({
                title: "提示",
                content: '图片保存失败，您需要开启相册权限并且重新保存,是否开启?',
                success: res => {
                  if (res.confirm) {
                    wx.openSetting({
                      success: (res) => {
                        if (res.authSetting['scope.writePhotosAlbum']) {
                          this.canvasClick();
                        } else {
                          wx.showToast({
                            title: '获取权限失败,无法使用保存图片或视频到您的相册',
                            icon: 'none'
                          })
                        }
                      },
                    })
                  }
                }
              })
            }
          })
        } else {
          this.canvasClick();
        }
      }
    })
  },
  canvasClick() {
    if (this.data.isSpecial) {
      this.canvasClick1();
      return false
    }
    let headPicUrl = this.data.userInfo.headPicUrl ? this.data.userInfo.headPicUrl.replace(":443", '') : ''; //this.data.doorwayPic.replace(":443", '');

    if (!headPicUrl) {
      wx.showToast({
        title: '您尚未维护自己的头像，暂时无法保存名片',
        icon: 'none'
      })
      return false
    }

    this.setData({
      isDisable: true
    })
    wx.showLoading({
      title: '名片生成中...',
    })

    let background = this.data.background.replace(":443", '') || this.data.imgUrl + 'shopimg/minebg.png'; //背景图  
    let image1 = this.localImge(background);
    let image2 = this.localImge(this.data.wxCode);
    let image3 = this.localImge(headPicUrl)
    Promise.all([image1, image2, image3]).then(res => {
      console.log(res);
      let background1 = res[0];
      let ecode1 = res[1];
      let headPicUrl1 = res[2]
      let top = 20;
      let left = 20;
      const ctx = wx.createCanvasContext("businessCard");
      // 画布背景色
      ctx.setFillStyle("#ffffff");
      //画布大小 
      ctx.fillRect(0, 0, this.data.width, this.data.height);
      // 背景图
      ctx.drawImage(background1, 0, 0, this.data.width, this.data.height);
      // logo
      ctx.drawImage('../../images/index/logo.png', 20, 20, 43, 32);

      ctx.fillStyle = this.data.fontColor || '#ffe5ca';
      // 店铺名字
      ctx.setFontSize(15);
      ctx.fillText(this.data.stroeInfo.storeName || '', 83, 40);
      // 专卖店
      ctx.setFontSize(10);
      this.drawText(ctx, this.data.stroeInfo.storeDesc || "", 83, 58, 389, 180)
      // 二维码
      this.circleImg(ctx, ecode1, 280, top, 20, 20)
      // 头像图片
      this.circleImg(ctx, headPicUrl1 || '../../images/logo/logo1.png', 10, 110, 25, 25)
      // 名字 店主||店长||店员
      ctx.setFontSize(18);
      let member = ''
      if (this.data.userInfo.userType == 4) {
        member = '店主'
      } else if (this.data.userInfo.userType == 5) {
        member = '店长'
      } else if (this.data.userInfo.userType == 6) {
        member = '店员'
      }
      ctx.fillText(this.data.userInfo.realName + ' ' + member, 83, 126);
      // 电话图标 
      ctx.drawImage('../../images/icon/tel1.png', 83, 138, 10, 10);
      // 电话号码
      ctx.setFontSize(11);
      ctx.fillText(this.data.userInfo.tel || '', 100, 148);
      // 地址图标
      ctx.drawImage('../../images/icon/adress.png', 83, 156, 10, 10);
      // 详细地址
      ctx.setFontSize(11);
      ctx.fillText(this.data.stroeInfo.storeAddressDetail || '', 100, 166);
      ctx.save();
      ctx.draw(false, () => {
        wx.canvasToTempFilePath({
          canvasId: "businessCard",
          success: res => {
            wx.hideLoading();
            this.setData({
              shopCard: res.tempFilePath
            });
            console.log("成功" + this.data.shopCard)
            this.downFn();
          },
          fail: err => {
            console.log('生成失败', err);
          }
        });
      });

    }).catch(err => {
      console.log(err);
      wx.hideLoading();
      wx.showToast({
        title: '图片加载失败,请返回重试',
        icon: 'none'
      })
    })
  },
  //特殊名片生成
  canvasClick1() {
    this.setData({
      isDisable: true
    })
    if (this.data.isSpecial) {
      //特殊名片
      this.setData({
        width: 355,
        height: 208
      })
    } else {
      this.setData({
        width: 355,
        height: 164,
      })
    }
    wx.showLoading({
      title: '名片生成中...',
    })
    let {
      storeName,
      storeDesc,
      storeAddressDetail
    } = this.data.stroeInfo;
    let {
      userType,
      realName,
      tel
    } = this.data.userInfo;

    let background = this.data.background.replace(":443", '') || this.data.imgUrl + 'shopimg/minebg.png'; //背景图  
    let image1 = this.localImge(background);
    let image2 = this.localImge(this.data.wxCode);

    Promise.all([image1, image2]).then(res => {
      console.log(res);
      let background1 = res[0];
      let ecode1 = res[1];
      const ctx = wx.createCanvasContext("businessCard");
      // 画布背景色
      ctx.setFillStyle("#ffffff");
      //画布大小 
      ctx.fillRect(0, 0, this.data.width, this.data.height);
      // 背景图
      ctx.drawImage(background1, 0, 0, this.data.width, this.data.height);

      ctx.font = 'normal bold 14px sans-serif';
      ctx.fillStyle = this.data.fontColor || '#ffe5ca';


      // 店铺名字
      //ctx.fillText(this.data.stroeInfo.storeName || '', 110, 35);
      this.drawText(ctx, storeName || '', 110, 35, 389, 180)

      ctx.font = 'normal 12px sans-serif';
      //判断门店的字数是否要换行
      if (storeName.length > 12) {
        // 专卖店
        this.drawText(ctx, storeDesc || "", 110, 69, 389, 180)
      } else {
        // 专卖店
        this.drawText(ctx, storeDesc || "", 110, 52, 389, 180)
      }

      // 二维码
      this.circleImg(ctx, ecode1, 280, 15, 30, 30);

      //店员名字
      realName = realName.slice(0, 1) + ' ' + realName.slice(1)
      ctx.font = 'normal bold 25px sans-serif';
      ctx.fillText(realName, 10, 130);

      //身份
      let member = ''
      if (userType == 4) {
        member = '店主'
      } else if (userType == 5) {
        member = '店长'
      } else if (userType == 6) {
        member = '店员'
      }
      ctx.font = 'normal 14px sans-serif';
      ctx.fillText('/' + member, realName.length * 25, 130);

      //手机号
      ctx.font = 'normal 12px sans-serif';
      ctx.fillText('Mob:' + tel, 10, 155);

      // 详细地址
      ctx.fillText('Add:', 10, 170);
      this.drawText(ctx, storeAddressDetail, 35, 170, 389, 130)

      ctx.save();
      ctx.draw(false, () => {
        wx.canvasToTempFilePath({
          canvasId: "businessCard",
          success: res => {
            wx.hideLoading();
            this.setData({
              shopCard: res.tempFilePath
            });
            console.log("成功" + this.data.shopCard)
            this.downFn();
          },
          fail: err => {
            console.log('生成失败', err);
          }
        });
      });

    }).catch(err => {
      console.log(err);
      wx.hideLoading();
      wx.showToast({
        title: '图片加载失败,请返回重试',
        icon: 'none'
      })
    })
  },
  //生成本地图片
  localImge: function (src) {
    console.log('src', src);
    return new Promise(function (resolve, reject) {
      wx.downloadFile({
        url: src,
        success: function (res) {
          resolve(res.tempFilePath);
        },
        fail: err => {
          reject(err)
        }
      });
    });
  },
  //保存图片
  downFn() {
    let imgurl = '';
    wx.showLoading({
      title: '保存中...',
    })
    imgurl = this.data.shopCard;
    console.log(imgurl)
    wx.saveImageToPhotosAlbum({
      filePath: imgurl,
      success: res => {
        wx.hideLoading()
        wx.showToast({
          title: "保存成功，从相册中分享到朋友圈吧",
          icon: "none",
          duration: 4000
        });
        this.setData({
          isDisable: false
        })
        this.addNum();
      },
      fail: function (err) {
        console.log(err)
        if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
          wx.hideLoading();
          wx.showModal({
            title: "提示",
            content: '图片保存失败，您需要开启相册权限并且重新保存,是否开启?',
            success: res => {
              if (res.confirm) {
                wx.openSetting({
                  complete: (res) => {
                    console.log(res);
                  },
                })
              }
            }
          })
        }
      }
    });
  },
  addNum: function () {
    //type 1 活动名片 2商品名片 3店铺名片
    common.requestAjax('/api/user-service/v1/storeDownloadCount/addCardAmount?orgSeq=' + getApp().globalData.shopInfo.orgSeq + '&type=' + 3, 'POST').then(res => {}).catch(err => {
      console.log(err);
    })
  },
  // 获得小程序码
  getWxCode() {
    let data = {
      type: 3, //1活动分享   2商品分享 3 店铺分享
      page: "pages/shop/index",
      //活动type==3 店铺type==4
      sceneStr: getApp().globalData.userId + ',' + getApp().globalData.shopInfo.orgSeq + ',' + 4,
      appid: getApp().globalData.appId,
      secret: getApp().globalData.wx_code,
      width: 300,
      orgSeq: getApp().globalData.shopInfo.orgSeq,
      userId: getApp().globalData.userId,
      phone: this.data.userInfo.tel
    }
    common.requestAjax('/api/file-service/v1/share/appletCode', 'POST', data).then(res => {
      if (res.data.code) {
        let wxCode = res.data.url.replace(":443", '');
        this.setData({
          wxCode,
        })
      }
    }).catch(err => {
      console.log(err);
    })
  },
  //获得背景图和背景色
  queryStoreCardConfig() {
    let data = {
      orgSeq: getApp().globalData.orgSeq,
      userId: app.globalData.userId,
    }
    common.requestAjax('/api/user-service/v1/StoreCard/queryStoreCardConfig', 'POST', data).then(res => {
      if (res.data.code == 1) {
        this.setData({
          background: res.data.result.cardPic, //背景图
          fontColor: res.data.result.fontColor, //字体颜色
          storeDesc: res.data.result.storeDesc, //描述
          cardName: res.data.result.cardName, //卡片风格
          doorwayPic: res.data.result.headPicUrl, //门头照
          isSpecial: res.data.result.isSpecial
        })
        console.log(this.data.background)
      }
    }).catch(err => {
      console.log(err);
    })
  },
  // 圆形图片
  circleImg: function (ctx, img, x, y, r) {
    ctx.save()
    ctx.beginPath()
    var d = 2 * r;
    var cx = x + r;
    var cy = y + r;
    ctx.arc(cx, cy, r, 0, 2 * Math.PI);
    ctx.clip();
    ctx.drawImage(img, x, y, d, d);
    ctx.restore()
  },
  // 超出换行
  drawText: function (ctx, str, leftWidth, initHeight, titleHeight, canvasWidth) {
    var lineWidth = 0;
    var lastSubStrIndex = 0; //每次开始截取的字符串的索引
    for (let i = 0; i < str.length; i++) {
      lineWidth += ctx.measureText(str[i]).width;
      if (lineWidth > canvasWidth) {
        ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); //绘制截取部分
        initHeight += 16; //16为字体的高度防止文字重叠
        lineWidth = 0;
        lastSubStrIndex = i;
        titleHeight += 30;
      }
      if (i == str.length - 1) { //绘制剩余部分
        ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);
      }
    }
    // 标题border-bottom 线距顶部距离
    titleHeight = titleHeight + 10;
    return titleHeight
  },
  // canvas绘制图片结束
  prewImage() {
    wx.previewImage({
      urls: [this.data.wxCode],
      complete: (res) => {},
      current: this.data.wxCode,
      fail: (res) => {},
      success: (res) => {},
    })
  },
  // 活动名片分享
  activeShare: function (e) {
    wx.navigateTo({
      url: '../shopShare/index',
    })
  },
  // 问题反馈
  problemFeedback: function () {
    wx.navigateTo({
      url: './workOrder/workOrder',
    })
  },
  // 开票记录
  billingRecord: function () {
    wx.navigateTo({
      url: './billing/billing',
    })
  },
  shareCard: function (e) {
    // 0保存名片  1跳转编辑
    if (e.currentTarget.dataset.type == 0) {

    } else {
      wx.navigateTo({
        url: './editor/index',
      })
    }
  },
  // 对账
  reconciliation: function () {
    wx.navigateTo({
      url: './reconciliation/reconciliation',
    })
  },
  // 数据看板
  panelData: function () {
    wx.navigateTo({
      url: './panelData/panelData',
    })
  },
  // 邀请业务员
  shareEmploy: function () {
    wx.navigateTo({
      url: './shareEmploy/shareEmploy',
    })
  },
  // 中奖记录
  winningRecord: function (e) {
    wx.navigateTo({
      url: '/pages/myCenter/winningRecordList/winningRecordList',
    })
  },
  // 常见问题
  commonProblem: function (e) {
    wx.navigateTo({
      url: '/pages/myCenter/commonProblem/commonProblem',
    })
  },
  // 兑换酒管理
  changeMengent: function (e) {
    wx.navigateTo({
      url: '/pages/myCenter/changeManagement/changeManagement',
    })
  },
  // 我的配送单
  mineOrder: function (e) {
    wx.navigateTo({
      url: '/pages/myOrderMgt/index',
    })
  },
  // 编辑名片
  editoInfo: function (e) {
    let routeUrl = '/pages/myCenter/editInfo/editInfo';
    let routeType = 'navigateTo';
    let params = '';
    common.routeLink(routeUrl, params, routeType)
  },
  getInfo: function (e) {
    let data = {
      userId: this.data.userId,
      orgSeq: this.data.orgSeq
    }
    common.requestAjax('/api/user-service/v1/foreign/getUserAndStoreInfo', 'GET', data).then(res => {
      this.setData({
        stroeInfo: res.data.storeInfoDTO,
        userInfo: res.data.userInfoDTO,
      })
      this.getWxCode() //获得小程序码
      this.queryStoreCardConfig() //获得店铺背景图和背景色
    }).catch(err => {
      console.log(err);
    })
  },
  // 品鉴酒兑换管理数量
  queryTaskAmount: function (e) {
    let data = {
      orgSeq: this.data.orgSeq
    }
    common.requestAjax('/api/promotion-service/v1/memberWine/queryTaskAmount', 'GET', data).then(res => {
      console.log(res)
      this.setData({
        tagsNum: res.data.result.amount
      })
    }).catch(err => {
      console.log(err);
    })
  },
  onLoad: function (options) {
    let orgSeq = app.globalData.orgSeq;
    let userId = app.globalData.userId;
    this.setData({
      orgSeq: orgSeq,
      userId: userId,
      user: app.globalData.shopInfo.userType,
    })
  },
  onShow: function () {
    this.getInfo();
    this.queryTaskAmount();
    this.queryDeliverNum();
    //this.getPageList(1,1)
    //元春活动数量获取
    this.getSpringActNum();
    //直播活动获取
    //this.getLiveActivity();
  },
  getSpringActNum() {
    if (app.globalData.userId) {
      common.requestAjax('/api/file-service/v1/newyear/queryUnconfirmedHelpApplyNum?orgSeq=' + app.globalData.userId, 'POST', {}).then(res => {
        this.setData({
          yuanNum: res.data.result || 0
        })
      })
    }
  },
  gotoSpringPage() {
    wx.navigateTo({
      url: '/pages/springPage/index',
    })
  },
  shareAppMessage: function () {},
  exitBtn() {
    wx.showModal({
      title: '提示',
      content: '是否退出登录？',
      success: res => {
        if (res.confirm) {
          wx.setStorageSync('token', '');
          wx.setStorageSync('isLogin', false);
          app.globalData.userType = 0; //用户类型(1集团人员2战区人员3基地业务员4店主5店长6店员)
          app.globalData.orgSeq = '';
          app.globalData.orgList = ''; //用户列表
          app.globalData.userId = ''; //用户id
          app.globalData.yaoQorgSeq = ''; //邀请的门店编码
          app.globalData.shopInfo = ''; //切换的店铺信息
          app.globalData.defaultShopInfo = ''; //默认门店信息
          wx.reLaunch({
            url: '/pages/login/index',
          })
        }
      }
    })
  },
  queryDeliverNum() {
    let data = {
      orgSeq: app.globalData.orgSeq
    }
    common.requestAjax('/api/promotion-service/v1/winningRecord/queryDeliverNum', 'POST', data).then(res => {
      if (res.data.code) {
        this.setData({
          deliverNum: res.data.result.deliverNum
        })
      }
    })
  },
  toPointList() {
    wx.navigateTo({
      url: '/pages/pointList/list/index',
    })
  },
  //创建直播间
  toCreateLive() {
    this.setData({
      creatModelShow: true,
      wxUsername: ""
    })

  },
  toCreateLiveConfrim() {
    if (!this.data.wxUsername) {
      wx.showToast({
        title: "请先填写主播的微信号！",
        icon: "none"
      })
      return false;
    }
    common.requestAjax('/api/file-service/v1/zbHomeApi/addrole', 'POST', {
      "role": 2,
      "username": this.data.wxUsername
    }).then(res => {
      if (res.data.code) {
        this.hideModal();
        //前往创建直播间页面
        wx.navigateTo({
          url: '/pages/myCenter/liveRoom/index?wxUsername=' + this.data.wxUsername,
        })
        return
        this.creatLiveRoom();
      } else {
        let errorCode = res.data.message.split(':')[0];
        if (errorCode === "400002") {
          //主播角色需要认证
          this.setData({
            showApproveModel: true,
            approveImage: res.data.result
          })
        } else {
          wx.showToast({
            title: res.data.message,
            icon: "none"
          })
        }
      }
    })
  },
  getPlayerWxNo(e) {
    this.setData({
      wxUsername: e.detail.value.trim()
    })
  },
  hideModal() {
    this.setData({
      creatModelShow: false,
    })
  },
  hideApproveModal() {
    this.setData({
      showApproveModel: false
    })
  },
  // 远程图片加载404显示默认图
  onImageError: function (ev) {
    console.log("onImageError", ev);
    var _that = this;
    app.errImgFun(ev, _that);
  },

  /**
   * 获取直播活动详情
   * 店长且有活动的情况下开放入口
   * **/
  getLiveActivity() {
    common.requestAjax("/api/flashsale-service/v1/zbRelatedApi/getZbEntrance", "GET", {
      orgSeq: app.globalData.orgSeq
    }).then(res => {
      if (res.data.code) {
        this.setData({
          liveActivityInfo:res.data.result || ""
        })
      }
    })
  },
  //直播活动
  toLiveDetail(){
      wx.navigateTo({
        url: '/pages/myCenter/liveActivity/index',
      })
  }
})